import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
      return
    }

    if (!store.getters.name) {
      await store.dispatch('user/getUserInfoAction')
      const user = store.state.user
      const menus = user.userInfo.roles.menus // 配置的权限列表, menus是前端路由路径不带/  employee /employee

      console.log('menus  ----->  ', menus)
      console.log('asyncRoutes  ----->  ', asyncRoutes)
      const newList = asyncRoutes.filter(v => {
        return menus.includes(v.name)
      })

      router.addRoutes([...newList, { path: '*', redirect: '/404', hidden: true }])
      store.commit('user/setRoutes', newList)
      next(to.path)
    }

    next()
    return
  }

  if (whiteList.includes(to.path)) {
    next()
    return
  }

  next('/login')
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
